# !/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Blueprint, session, request
from app.util import get_user, add_user, db_save, check_pw ,random_str
from app.util.md5 import md5_update
from app.util.response import resp, resp_with_user

user = Blueprint('user', __name__)


def is_login_by_session():
    _uid = session.get('userId', None)
    _u = None
    if _uid is not None:
        _u = get_user(_id=_uid)
    return False if _u is None else True


def get_user_by_session():
    _uid = session.get('userId', None)
    _u = None
    if _uid is not None:
        _u = get_user(_id=_uid)
    return _u


@user.route('/islogin', methods=['GET'])
def is_login():
    return resp_with_user()


@user.route('/login', methods=['POST'])
def login():
    if is_login_by_session():
        return resp(msg_id=-3)
    _d = request.get_json()
    name = _d.get('username')
    if name is None:
        return resp(msg_id=-100)
    password = _d.get('password')
    if password is None:
        return resp(msg_id=-100)
    _user = get_user(name=name)
    if _user and check_pw(password, _user.salt, _user.password):
        session['userId'] = _user.id
        if _user.first_login:
            return resp(msg_id=10)
        return resp(msg_id=1)
    return resp(msg_id=-1)


@user.route('/logout', methods=['GET', 'POST'])
def logout():
    del session['userId']
    return resp_with_user()


# @user.route('/salt', methods=['POST'])
# def salt():
#     _d = request.get_json()
#     name = _d.get('username')
#     if name is None:
#         return resp(msg_id=-100)
#     _user = get_user(name=name)
#     if _user and _user.salt:
#         return resp(msg_id=0, data={
#             salt: _user.salt
#         })


@user.route('/add', methods=['POST'])
def add():
    _d = request.get_json()
    name = _d.get('username')
    if name is None:
        return resp(msg_id=-100)
    pw = add_user(name)
    return resp(msg_id=100, data={
        'password': pw
    })


@user.route('/change_pw_token', methods=['POST'])
def cpt():
    _d = request.get_json()
    _user = get_user_by_session()
    if _user is None:
        return resp(msg_id=-12)
    password = _d.get('password')
    if password is None:
        return resp(msg_id=-100)
    if check_pw(password, _user.salt, _user.password):
        _t = random_str(20)
        session['cpt'] = _t
        return resp_with_user(msg_id=100, data={
            'cpt': _t
        })
    return resp_with_user(msg_id=-1)


@user.route('/change_pw', methods=['POST'])
def change():
    _d = request.get_json()
    token = _d.get('cpt')
    if token is None:
        return resp(msg_id=-100)
    new = _d.get('new_password')
    if new is None:
        return resp(msg_id=-100)
    _user = get_user_by_session()
    if _user is None:
        return resp(msg_id=-12)
    _t = session.get('cpt', None)
    if _t and _t == token:
        _user.password = md5_update(new, _user.salt)
        if _user.first_login is True:
            _user.first_login = False
        db_save(add_models=[_user])
        return resp_with_user(msg_id=100)
    return resp_with_user(msg_id=-1)
